import config from './config'

interface IApiResult<T = any> {
	code : number
	msg : string
	data ?: T
}

interface IWsResult {
	type : 'api' | 'sysmsg',
	url ?: string,
	data ?: {
		code : number,
		msg : string,
		data ?: any
	}
}

interface IRequestUpload {
	files : string
	type : string
	success : Function
	fail : Function
	complete : Function
}

export default {
	post: (url : string, data : any = {}) => {
		return new Promise(
			(
				resolve : (value : IApiResult) => void,
				reject
			) => {
				uni.request({
					url: config.apiHost + url,
					data,
					method: 'POST',
					header: {
						'token': uni.getStorageSync('token') || ''
					},
					success: (result) => {
						if (result.statusCode === 200) {
							resolve(result.data as IApiResult)
						} else if (result.statusCode === 401) {
							uni.showToast({
								icon: 'fail',
								title: '请登录!'
							})
							uni.redirectTo({
								url: '/pages/login/login'
							})
						} else {
							reject({
								code: result.statusCode,
								msg: result.errMsg
							})
						}
					},
					fail: (err) => {
						console.log(err)
						reject({
							code: 0,
							msg: err
						})
					}
				})
			})
	},
	upload: async function (obj: IRequestUpload) {
		uni.uploadFile({
			url: config.apiHost + '/upload',
			filePath: obj.files,
			name: 'image',
			formData: {
				type: obj.type
			},
			header: {
				'token': uni.getStorageSync('token') || ''
			},
			fileType: 'image',
			success: res => obj.success(res),
			fail: () => {
				if (obj.fail) {
					obj.fail()
				}
			},
			complete: () => {
				if (obj.fail) {
					obj.complete()
				}
			}
		})
	},
	ws: async function (url : string, params : any) {
		if (getApp().globalData.connected) {
			return new Promise((resolve, reject) => {
				uni.sendSocketMessage({
					data: JSON.stringify({ url, params }),
					success: result => resolve(result),
					fail: result => reject(result),
					complete: () => {
						resolve({})
					}
				})
			})
		} else {
			return Error('socket is undefind')
		}
	},
	onWs: (callback : (value : IWsResult) => void) => {
		uni.onSocketMessage((res) => {
			callback(JSON.parse(res.data))
		})
	}
}